from socket import *
from multiprocessing import Process,Queue
a={}
def xxzf(s, data, addr):
    for j,l in a.items():
        if addr==l:
            for w,x in a.items():
                if addr!=x:
                    s.sendto((j+':'+data).encode(),x)
def re(s,v):
    while True:
        date,addr=s.recvfrom(1024)
        data=date.decode()
        if len(a)==0:
            a[data]=addr
            s.sendto('cg'.encode(),addr)
            v.put(a)
        else:
            if addr in a.values():
                xxzf(s,data,addr)
            else:
                if data in a:
                    s.sendto('名字已注册，重新输入'.encode(),addr)
                else:
                    a[data] = addr
                    s.sendto('srcg'.encode(),addr)
                    v.put(a)
                    for i in a.values():
                        if i!=addr:
                            s.sendto((data+'加入群聊').encode(), i)
def main(s,addr,v):
    s.bind(addr)
    re(s,v)
def srxx(s,v):
    d=v.get()
    while True:
        z=input('请输入消息：')
        if v.empty():
            m=('服务器消息：'+z).encode()
            for i in d.values():
                s.sendto(m,i)
        else:
            while True:
                d = v.get()
                if v.empty():
                    break
            m = ('服务器消息：' + z).encode()
            for i in d.values():
                s.sendto(m, i)

if __name__ == '__main__':
    v=Queue()
    s = socket(AF_INET, SOCK_DGRAM)
    addr = ('0.0.0.0', 8090)
    m=Process(target=main,args=(s,addr,v))
    m.start()
    srxx(s,v)